package club.banyuan.hrms.servlet;

import club.banyuan.User;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

@WebServlet(name = "ConfigandContextServlet", urlPatterns = "/st7", initParams = {
        @WebInitParam(name = "username", value = "zhangsan"),
        @WebInitParam(name = "password", value = "123456")
})
public class ConfigandContextServlet extends HttpServlet {
    @Override
    public void init() throws ServletException {
        User user = new User("lisi", 20);
        getServletContext().setAttribute("user", user);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/plain;charset=utf-8");

        // 获取config初始化参数
        ServletConfig servletConfig = getServletConfig();
        String username = servletConfig.getInitParameter("username");
        String password = servletConfig.getInitParameter("password");
        response.getWriter().println("username: " + username);
        response.getWriter().println("password: " + password);

        response.getWriter().println("-----------------------------------------------");

        // 获取context初始化参数
        ServletContext servletContext = servletConfig.getServletContext();
        Enumeration<String> initParameterNames = servletContext.getInitParameterNames();
        while (initParameterNames.hasMoreElements()) {
            String name = initParameterNames.nextElement();
            String value = servletContext.getInitParameter(name);
            response.getWriter().println(name + ": " + value);
        }

        response.getWriter().println("-----------------------------------------------");

        // 获取ServletContext的属性
        User user = (User) servletContext.getAttribute("user");
        response.getWriter().println("user name: " + user.getName());
        response.getWriter().println("user age: " + user.getAge());
    }
}
